package com.hdax.dm.user.controller;

import com.hdax.dm.auth.code.CodeEnum;
import com.hdax.dm.auth.exception.DmException;
import com.hdax.dm.entity.user.User;
import com.hdax.dm.token.TokenUtil;
import com.hdax.dm.user.dto.TokenDto;
import com.hdax.dm.user.service.UserService;
import com.hdax.dm.utils.CommonResponse;
import com.hdax.dm.utils.ResponseUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(path = "/user")
public class UserLoginController {

    //用于java操作redis中的string
    //Map<String, String>
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private UserService userService;

    @PostMapping(path = "msg/login")
    public CommonResponse<TokenDto> login(@RequestBody Map<String, String> params) throws DmException{
        TokenDto tokenDto = null;
        String phone = params.get("phone");
        String vcode = params.get("vcode");
        String redisKey = phone +"_vcode";
        //redis存储的真实有效的验证码
        String code = stringRedisTemplate.opsForValue().get(redisKey);
        if(code == null){
            throw new DmException(CodeEnum.USER_VCODE_NOT_EXISTS);
        }
        if(vcode == null || !vcode.equals(code)){
            throw new DmException(CodeEnum.USER_VCODE_INVALID);
        }
        if(vcode.equals(code)){
            System.out.println("登录成功！");
            //数据库查询用户
            User user =userService.user(phone);

            Map<String,String> tokenParams = new HashMap<>();
            tokenParams.put("nickName",user.getNickName());
            tokenParams.put("phone",user.getPhone());
            tokenParams.put("realName",user.getRealName());
            tokenParams.put("id",user.getId().toString());

            String token = tokenUtil.createToken(tokenParams);

            //存储token到redis，过期时间为4h
            stringRedisTemplate.opsForValue().set("token:user:"+user.getId(),token, 4,TimeUnit.HOURS);

            tokenDto = new TokenDto();
            tokenDto.setToken(token);
//            tokenDto.setGenTime(date.getTime());
//            tokenDto.setExpTime(1000 * 60 * 60 * 2);
            tokenDto.setUserId(user.getId());
            tokenDto.setNickName(user.getNickName());
            tokenDto.setRealName(user.getRealName());
            tokenDto.setPhone(phone);
        }
        return ResponseUtil.returnSuccess(tokenDto);
    }


    @PostMapping(path = "msg")
    public CommonResponse msg(@RequestBody Map<String,String> params)
            throws DmException,Exception {
        String phone = params.get("phone");

        Object value = stringRedisTemplate.opsForValue().get(phone+"_vcode");


        if (value != null) {
            //60s内不能重复获取
            throw new DmException(CodeEnum.USER_VCODE_WITHOUT_TIMEOUT);
        }

        //生成四位随机数
        String num = "0123456789";

        StringBuffer vcode = new StringBuffer();
        for (int i = 1; i <= 4 ; i++) {
            char n = num.charAt((int)(Math.random() * num.length()));
            vcode.append(n);
        }
        //redis存储生成的验证码
        stringRedisTemplate.opsForValue().set(phone+"_vcode",vcode.toString(),60, TimeUnit.SECONDS);
        Map<String,String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("vcode",vcode.toString());
        //发送消息到mq
        //直接模式  默认交换器 exchange=""
        //队列名称认为是交换器名称
        //rabbitTemplate.convertAndSend("dmsms",msg);

        return ResponseUtil.returnSuccess(vcode.toString());
    }

}
